<template>
  <div class="container">
    <div v-show="loading" class="well loading">正在加载中，请耐心等待...</div>
    <div v-show="!loading" class="well" ref="output"></div>
  </div>
</template>

<script>
import { getExtend, render } from './components/util'
// import { parse } from 'qs'

export default {
  props: {
    fileUrl: {
      type: String,
      default: '',
    },
    name: String,
  },
  data() {
    return {
      // 加载状态跟踪
      loading: false,
      // 隐藏头部，当基于消息机制渲染，将隐藏
      hidden: false,
      arrayBuffer: null,
    }
  },
  async mounted() {
    this.loading = true
    this.getArrayBuffer()
  },
  methods: {
    getArrayBuffer() {
      const _this = this
      const xhr = new XMLHttpRequest()
      xhr.open('GET', _this.fileUrl, true)
      xhr.responseType = 'arraybuffer'
      xhr.onload = async function () {
        if (xhr.status === 200) {
          // _this.arrayBuffer = new Uint8Array(xhr.response)
          _this.arrayBuffer = xhr.response
          try {
            await _this.displayResult()
          } catch (error) {
          } finally {
            _this.loading = false
          }
        }
      }
      xhr.send()
    },
    displayResult() {
      // 取得文件名
      const name = this.name
      // 取得扩展名
      const extend = getExtend(name)
      // 输出目的地
      const { output } = this.$refs
      // 生成新的dom
      const node = document.createElement('div')
      // 添加孩子，防止vue实例替换dom元素
      if (this.last) {
        output.removeChild(this.last.$el)
        this.last.$destroy()
      }
      const child = output.appendChild(node)
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) =>
        render(this.arrayBuffer, extend, child).then(resolve).catch(reject)
      )
    },
  },
}
</script>
<style scoped>
:deep(.docx-wrapper) {
  background: none !important;
}
.well {
  display: block;
  width: 100%;
  min-height: calc(100vh - 44px);
  overflow: hidden;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
</style>
